package lumis.portal.presentation.tag.page;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import lumis.portal.PortalException;
import lumis.portal.PortalRequestParameters;
import lumis.portal.PortalStringResource;
import lumis.portal.authentication.SessionConfig;
import lumis.portal.manager.ManagerFactory;
import lumis.portal.page.PageConfig;
import lumis.portal.page.PageWebResource;
import lumis.portal.presentation.PresentationControllerHtml.DataPreviewMode;
import lumis.portal.presentation.core.HTMLFragmentComponent;
import lumis.portal.presentation.core.LayoutFilePage;
import lumis.portal.servicecontainer.ServiceContainerUrl;
import lumis.portal.transaction.PortalTransactionFactory;
import lumis.portal.user.UserConfig;
import lumis.util.ITransaction;

import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.MarkupStream;
import org.apache.wicket.util.string.AppendingStringBuffer;

/**
 * Injects the page's body header component.
 * @version $Revision: 13321 $ $Date: 2011-08-08 11:32:13 -0300 (Mon, 08 Aug 2011) $
 * @since 6.0.0
 */
public class PageBodyHeaderComponent extends HTMLFragmentComponent 
{
	/**
	 * Serial version identifier.
	 * @since 6.0.0
	 */
	private static final long serialVersionUID = 1L;

	public PageBodyHeaderComponent(String id) 
	{
		super(id);
	}

	@Override
	protected CharSequence getHTMLFragment(MarkupStream markupStream, ComponentTag openTag) 
	{
		AppendingStringBuffer bodyHeader = new AppendingStringBuffer(1500);
		try
		{
			LayoutFilePage page = ((LayoutFilePage)getPage());
			SessionConfig sessionConfig = SessionConfig.getCurrentSessionConfig();
			PageConfig pageConfig = page.getPageWebResource().getPage();
			PageWebResource webResource = page.getPageWebResource();
			DataPreviewMode dataPreviewMode = page.getPageRenderer().getDataPreviewMode();
			
			ServiceContainerUrl formActionURL = new ServiceContainerUrl(ServiceContainerUrl.RENDER_URL);
			formActionURL.setPageId(pageConfig.getId());
			if (pageConfig.getType() == PageConfig.PAGE_TYPE_ADMIN)
				formActionURL.setChannelId(pageConfig.getChannelId());
			formActionURL.setRunTimeServiceInstanceId(webResource.getRunTimeServiceInstanceId());
			formActionURL.setRunTimeServiceInterfaceId(webResource.getRunTimeServiceInterfaceId());
			
			String callerInterfaceInstanceId = getRequest().getParameter(PortalRequestParameters.PAGE_PARAMETER_CALLER_INTERFACE_INST);
			if (callerInterfaceInstanceId != null)
				formActionURL.setParameter(PortalRequestParameters.PAGE_PARAMETER_CALLER_INTERFACE_INST, callerInterfaceInstanceId);
			
			// resolve the URL only if there is no callerInterfaceInstanceId and
			// it is not a cache generator request
			boolean resolveURL = callerInterfaceInstanceId == null && page.getGeneratorPageCacheId() == null && !webResource.isCacheEnabled(sessionConfig.getUserId().equals(UserConfig.USER_GUEST_ID));
			
			bodyHeader.append("<form style=\"display:none\" accept-charset=\"UTF-8\" id=\"LumisPortalForm\" action=\"" + formActionURL.toString(resolveURL).replaceAll("&(?!\\w+;)", "&amp;"));
			bodyHeader.append("\" method=\"post\"><div><input name=\""+PortalRequestParameters.PAGE_PARAMETER_PERSPECTIVE+"\" type=\"hidden\"/><input name=\""+PortalRequestParameters.PAGE_PARAMETER_MODE+"\" type=\"hidden\"/><input name=\"lumSafeRenderMode\" type=\"hidden\"/><input name=\"");
			bodyHeader.append(PortalRequestParameters.PAGE_PARAMETER_NEW);
			bodyHeader.append("\" type=\"hidden\" /><input name=\"");
			bodyHeader.append(PortalRequestParameters.PAGE_PARAMETER_PRINTING);
			bodyHeader.append("\" type=\"hidden\" />");
			bodyHeader.append("<input name=\"pageOriginalUrl\" type=\"hidden\" value=\""+formActionURL.toString(false).replaceAll("&(?!\\w+;)", "&amp;")+"\"/>");
			bodyHeader.append("<input name=\""+PortalRequestParameters.PAGE_PARAMETER_SERVICE+"\" type=\"hidden\" value=\"\"/>");
			bodyHeader.append("<input name=\""+PortalRequestParameters.PAGE_PARAMETER_SERVICE_INST+"\" type=\"hidden\" value=\"\"/>");
			bodyHeader.append("<input name=\""+PortalRequestParameters.PAGE_PARAMETER_INTERFACE+"\" type=\"hidden\" value=\"\"/>");
			bodyHeader.append("<input name=\""+PortalRequestParameters.PAGE_PARAMETER_INTERFACE_INST+"\" type=\"hidden\" value=\"\"/>");
			bodyHeader.append("<input name=\"");
			bodyHeader.append(PortalRequestParameters.PAGE_PARAMETER_PREVIOUS);
			bodyHeader.append("\" type=\"hidden\" value=\"");
			try
			{
				bodyHeader.append(URLEncoder.encode(page.getPreviousParametersXmlString(), "UTF-8"));
			}
			catch (UnsupportedEncodingException e)
			{
				throw new RuntimeException(e);
			}
			bodyHeader.append("\" /><input name=\"lumA\" type=\"hidden\" value=\"\"/><input name=\"lumDataPreviewMode\" type=\"hidden\" value=\"\"/><input name=\"LumisClientMessage\" type=\"hidden\" value=\"\"/></div></form>");

			bodyHeader.append("<form style=\"display:none\" accept-charset=\"UTF-8\" id=\"LumisPortalRenderInterfaceForm\" action=\"lumis/portal/controller/html/ServiceInterfaceInstanceControllerHtml.jsp?" + PortalRequestParameters.PAGE_PARAMETER_PAGEID + "=");
			bodyHeader.append(pageConfig.getId());
			if (pageConfig.getType() == 1)
			{
				bodyHeader.append("&amp;" + PortalRequestParameters.PAGE_PARAMETER_CHANNELID + "=");
				bodyHeader.append(pageConfig.getChannelId());
			}

			String pageCacheId = page.getGeneratorPageCacheId();
			if(pageCacheId != null)
			{
				ITransaction transaction = PortalTransactionFactory.createTransaction();
				try
				{
					transaction.begin();
					bodyHeader.append("&amp;" + PortalRequestParameters.PAGE_PARAMETER_PAGE_CACHE_ID + "=" + pageCacheId);
					transaction.commit();
				}
				finally
				{
					transaction.dispose();
				}
			}

			bodyHeader.append("\" method=\"post\">");

			bodyHeader.append("</form>");
			
			if(dataPreviewMode.previewModeEnabled && dataPreviewMode.stopPreviewModeEnabled)
			{
				bodyHeader.append("<script type=\"text/javascript\">function lumStopDataPreviewMode(){document.getElementById('lumDataPreviewMode').value='0';LumisPortal.onRefresh();}</script><noscript><!--Lumis portal script--></noscript>" +
						"<div style=\"position:absolute;background-color:#FFC763;padding:5px;margin:5px;color:white;top:0;right:0;filter:alpha(opacity=80);cursor:hand;\" onclick=\"lumStopDataPreviewMode()\">" +
						ManagerFactory.getLocalizationManager().localize("STR_STOP_PREVIEW_MODE", new PortalStringResource(), sessionConfig.getLocale())+"</div>");
			}
			
			return bodyHeader;
		}
		catch (PortalException e) 
		{
			throw new RuntimeException(e);
		}
	}
}
